package cn.demomaster.quickpicturer.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.demomaster.quickcompat.decorator.GridDividerItemDecoration;

import java.util.ArrayList;
import java.util.Map;

import cn.demomaster.quickpicturer.R;
import cn.demomaster.quickpicturer.adapter.FolderAdapter;
import cn.demomaster.quickpicturer.adapter.SimplePictureAdapter;
import cn.demomaster.quickpicturer.helper.PictureManager;
import cn.demomaster.quickpicturer.model.Folder;
import cn.demomaster.quickpicturer.model.ImageInfo;
import cn.demomaster.quickpicturer.util.PermissionUtil;

/**
 * 图片选择器
 */
public class PictureSelectorActitity extends BaseActivity {

    Activity mContext;

    /**
     * 横竖屏切换处理
     *
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mLayoutManager != null && mAdapter != null) {
            //切换为竖屏
            if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                mLayoutManager.setSpanCount(4);
            }
            //切换为横屏
            else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                mLayoutManager.setSpanCount(6);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_picture_selector);
        // 针对非AppCompat活动
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        setTitle(getResources().getString(R.string.image_selector));
        recyclerView_folder = findViewById(R.id.rv_folder);
        recyclerView_folder.setVisibility(View.GONE);
//        getActionBarTool().getRightView().setText(getResources().getString(R.string.send));
//        getActionBarTool().getRightView().setImageResource(0);
//        getActionBarTool().getRightView().setTextSize(DisplayUtil.dp2px(mContext,16));
//        getActionBarTool().getRightView().setOnClickListener(view -> {
//            //拍照完成，返回对应图片路径
//            Intent intent = new Intent();
//            ArrayList<Image> images = mAdapter.getImages();
//            Bundle bundle = new Bundle();
//            bundle.putSerializable(PHOTOHELPER_RESULT_PATHES, images);
//            intent.putExtras(bundle);
//            setResult(RESULT_OK, intent);
//            mContext.finish();
//        });
        //getActionBarTool().getActionBarTool().setBackgroundColor(getResources().getColor(R.color.white));
        //getActionBarTool().setStateBarColorAuto(true);
        btn_send = findViewById(R.id.btn_send);
        btn_send.setVisibility(View.GONE);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拍照完成，返回对应图片路径
                Intent intent = new Intent();
                ArrayList<ImageInfo> images = mAdapter.getImages();
                //Bundle bundle = new Bundle();
                //bundle.putSerializable(PHOTOHELPER_RESULT_PATHES, images);
                intent.putParcelableArrayListExtra("imagesInfos", images);
                //intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        init();
    }

    private TextView tvFolderName, tv_preview;
    private TextView btn_send;
    private ImageView iv_back;
    private RecyclerView rvImage;
    private SimplePictureAdapter mAdapter;
    private GridLayoutManager mLayoutManager;
    ArrayList<ImageInfo> imageArrayList = new ArrayList<>();

    private void init() {

        String[] permission = {Manifest.permission.READ_EXTERNAL_STORAGE};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            permission = new String[]{Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED};
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permission = new String[]{Manifest.permission.READ_MEDIA_IMAGES};
        } else {
            permission = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
        }
        PermissionUtil.requestPermissions(mContext, permission, new PermissionUtil.PermissionResultCallback() {
            @Override
            public void onPermissionsGranted(String[] strings) {
                initView();
            }

            @Override
            public void onPermissionsDenied() {

            }
        });
    }

    private void initView() {
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rl_mark.getVisibility() == View.VISIBLE) {
                    closeFolder();
                } else {
                    finish();
                }
            }
        });
        tv_preview = findViewById(R.id.tv_preview);
        tv_preview.setOnClickListener(v -> previewImage());
        tvFolderName = findViewById(R.id.tv_folder_name);
        tv_preview.setVisibility(View.GONE);
        rl_mark = findViewById(R.id.rl_mark);
        rl_mark.setVisibility(View.GONE);
        rvImage = findViewById(R.id.recy_picture_grid);
        rvImage.setLayoutManager(mLayoutManager);
        rl_mark.setOnClickListener(v -> closeFolder());
        tvFolderName.setOnClickListener(v -> {
            if (isInitFolder) {
                if (isOpenFolder) {
                    closeFolder();
                } else {
                    openFolder();
                }
            }
        });
        PictureManager.loadImageForSDCard(mContext, folders1 -> {
            mFolders = folders1;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    initAdapter();
                    initFolderList();
                }
            });
        });
    }

    private void previewImage() {
        PreviewActivity.startActivity(mContext,mAdapter.getImages(),0);
    }

    private int maxCount = 3;

    public void initAdapter() {
        // 判断屏幕方向
        Configuration configuration = getResources().getConfiguration();
        int spanCount = configuration.orientation == Configuration.ORIENTATION_PORTRAIT ? 4 : 6;
        mLayoutManager = new GridLayoutManager(this, spanCount);
        //设置分隔线
        rvImage.addItemDecoration(new GridDividerItemDecoration(mContext, spanCount));
        //设置增加或删除条目的动画
        rvImage.setItemAnimator(new DefaultItemAnimator());
        rvImage.setLayoutManager(mLayoutManager);
        maxCount = getIntent().getIntExtra("MaxCount", 0);
        imageArrayList = mFolders.get(0).getImages();
        mAdapter = new SimplePictureAdapter(mContext, imageArrayList, maxCount, true, rvImage);
        rvImage.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new SimplePictureAdapter.OnItemClickListener() {
            @Override
            public void onItemPreview(View view, int position, ImageInfo image) {
                ArrayList<ImageInfo> images = new ArrayList<>();
                images.add(image);
                PreviewActivity.startActivity(mContext, images, 0);
            }

            @Override
            public void onItemClick(View view, int position, Map<Integer, ImageInfo> map) {
                if (map == null || map.size() == 0) {
                    tv_preview.setVisibility(View.GONE);
                    btn_send.setVisibility(View.GONE);
                } else {
                    tv_preview.setVisibility(View.VISIBLE);
                    tv_preview.setText(mContext.getResources().getString(R.string.preview) + "(" + map.size() + "/" + maxCount + ")");
                    btn_send.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private ArrayList<Folder> mFolders;
    private Folder mFolder;
    private boolean isInitFolder;
    private boolean isOpenFolder;
    private RecyclerView recyclerView_folder;
    private ViewGroup rl_mark;

    /**
     * 初始化图片文件夹列表
     */
    private void initFolderList() {
        if (mFolders != null && !mFolders.isEmpty()) {
            isInitFolder = true;
            recyclerView_folder.setLayoutManager(new LinearLayoutManager(mContext));
            //设置分隔线
            //recyclerView_folder.addItemDecoration( new DividerGridItemDecoration(this ));
            //设置行级分割线使用的divider
            recyclerView_folder.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));

            FolderAdapter adapter = new FolderAdapter(mContext, mFolders);
            adapter.setOnFolderSelectListener(folder -> {
                setFolder(folder);
                closeFolder();
            });
            recyclerView_folder.setAdapter(adapter);
        }
    }

    /**
     * 设置选中的文件夹，同时刷新图片列表
     *
     * @param folder
     */
    private void setFolder(Folder folder) {
        if (folder != null && mAdapter != null && !folder.equals(mFolder)) {
            mFolder = folder;
            tvFolderName.setText((TextUtils.isEmpty(folder.getName()) ? mContext.getResources().getString(R.string.image) : folder.getName()));
            rvImage.scrollToPosition(0);
            mAdapter.refresh(folder.getImages(), false);
        }
    }

    /**
     * 弹出文件夹列表
     */
    private void openFolder() {
        if (!isOpenFolder) {
            rl_mark.setVisibility(View.VISIBLE);
            ObjectAnimator animator = ObjectAnimator.ofFloat(recyclerView_folder, "translationY",
                    -recyclerView_folder.getHeight(), 0).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    recyclerView_folder.setVisibility(View.VISIBLE);
                }
            });
            animator.start();
            isOpenFolder = true;
        }
    }

    /**
     * 收起文件夹列表
     */
    private void closeFolder() {
        if (isOpenFolder) {
            rl_mark.setVisibility(View.GONE);
            ObjectAnimator animator = ObjectAnimator.ofFloat(recyclerView_folder, "translationY",
                    0, recyclerView_folder.getHeight()).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    recyclerView_folder.setVisibility(View.GONE);
                }
            });
            animator.start();
            isOpenFolder = false;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && isOpenFolder) {
            closeFolder();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
}
